﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BeanboxSoftware.BeanMap.Internal
{
  internal static class EnumerableCollectionExtension
  {
    public static ICollection<T> ToEnumerableCollection<T>(this IEnumerable<T> enumer)
    {
      return new EnumerableCollection<T>(enumer);
    }
  }

  internal class EnumerableCollection<T> : ICollection<T>
  {
    private IEnumerable<T> _enumerable;
    private List<T> _list;

    private void PrepList()
    {
      if (_list == null)
      {
        _list = _enumerable.ToList();
      }
    }

    public EnumerableCollection(IEnumerable<T> enumer)
    {
      _enumerable = enumer;
      _list = null;
    }

    public void Add(T item) { throw new NotSupportedException(); }
    public void Clear() { throw new NotSupportedException(); }
    public bool Remove(T item) { throw new NotSupportedException(); }

    public bool Contains(T item)
    {
      return _enumerable.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
      PrepList();
      _list.CopyTo(array, arrayIndex);
    }

    public int Count
    {
      get 
      { 
        PrepList();  
        return _list.Count; 
      }
    }

    public bool IsReadOnly
    {
      get { return true; }
    }

    public IEnumerator<T> GetEnumerator()
    {
      return _enumerable.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }
  }
}
